from datetime import datetime

from flask import render_template, flash, redirect, request, abort
from flask_login import current_user

from app import login_required_with_check_scope
from app.admin import admin
from app.model.base import db
from app.model.order import Order, OrderStatus
from app.validator.order import OrderSendPackageForm


@admin.route('/order/list', methods=['GET'])
@login_required_with_check_scope
def order_list_ep():
    """
        管理员查看订单列表路由

    :arg:
        k: 搜索关键词, 可空
        p: 页码，可空

    :return:
        order: 订单列表
    """
    k = request.args.get('k', '', str)
    p = request.args.get('p', 1, int)
    pagination = Order.query.filter(
        Order.product_name.like('%' + k + '%')
    ).order_by(
        Order.create_time.desc()
    ).paginate(p, per_page=5)
    orders = pagination.items
    return render_template('admin/order/list.html', orders=orders, pagination=pagination)


@admin.route('/order/<order_id>', methods=['get'])
@login_required_with_check_scope
def order_detail_ep(order_id):
    """
        管理员查看订单列表页面路由

    :param
        order_id: 订单id

    :return:
        order: 订单实例对象
    """
    order = Order.query.filter_by(id=order_id).first()
    if not order:
        abort(404)
    return render_template('admin/order/detail.html', order=order)


@admin.route('/order/send_package', methods=['POST'])
@login_required_with_check_scope
def order_send_package_ep():
    """
        管理员发货

    :form:
        package_code: 快递单号

    :return: 重定向到来源页面
    """
    form = OrderSendPackageForm(request.form)
    if form.validate():
        order = Order.query.filter_by(id=form.order_id.data).first()
        if order:
            with db.auto_commit():
                order.send_package(form.package_code.data)
    flash(form.errors, 'form')
    return redirect(request.referrer)


@admin.route('/order/allow_cancel', methods=['post'])
@login_required_with_check_scope
def order_allow_cancel_ep():
    """
        管理员统一取消订单

    :form:
        order_id: 订单id
    """
    order_id = request.form.get('order_id', type=str)
    order = Order.query.filter_by(id=order_id).first()
    # 只能取消正在申请取消的订单
    if order and OrderStatus(order.status) == OrderStatus.REQUEST_CANCEL:
        with db.auto_commit():
            order.canceled()
    return redirect(request.referrer)
